# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


import database
tables = database.tables
get_tableobj = database.get_tableobj
from tables import session
from sqlalchemy.sql import and_, or_, not_

def select_string(connection, s, unique=False):
    if unique:
        r = connection.execute(s).fetchone()
    else:
        r = connection.execute(s).fetchall()
    if r:
        return r
    else:
        return False



def select_table(loader, table_name, *args, **kw):
    loader.log_function(__name__+'.select_table','INIT', table_name, args=args, kw=kw)
    #session = loader.session
    values =kw

    TableObj = get_tableobj(table_name)
    table = getattr(tables, table_name)
    query = session.query(TableObj)
    #if table_name = 'composizione_richiesta':

    #print dir(query.all()[0].c)
    #print query.select()
    table_index = None
    if hasattr(tables, table_name+'_index'):
        table_index = getattr(tables, table_name+'_index')
    unique = False

    if values:
        and_lst = []
        and_lst_unique = []
        for key, val in values.iteritems():
            table_attr = getattr(table.c,key)
            and_lst.append(table_attr == val)
            if table_attr.unique:
                and_lst_unique.append(getattr(table.c,key) == val)
                unique = True
            elif table_index:
                if table_index.unique:
                    for col in table_index.columns:
                        if key == col.name:
                            and_lst_unique.append(getattr(table.c,key)==val)
                            unique=True
        if unique:
            loader.logger.debug("Is unique: %s"%and_lst_unique)
            query = query.filter(and_(*and_lst_unique))

        else:
            query = query.filter(and_(*and_lst))
    ret = query.mapper.columns.keys(), query.all()
    loader.log_function(__name__+'.select_table', 'RET', ret)

    return ret


